<?php
/**
 * cms 信息服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\Collection as CollectionModel;
use app\common\model\Columns;
use app\common\model\Mods;
use app\common\model\Fields;
use app\common\model\Contents AS ContentsModel;
use app\common\model\Columns as ColumnsModel;
use think\Db;
use think\facade\Cache;

class Contents extends Base
{
    /**
     * 列表数据补充
     * @param  int   $column_id 栏目 id
     * @param  array $data      列表数据
     */
    public function listAttach($column_id, $data)
    {
        // 查询栏目信息
        $column     = Columns::field('tbname,mod_id')->where('id', $column_id)->find();
        $listField  = [];
        $dataAttach = [];
        if ($column) {
            // 查询系统模型信息
            $mod = Mods::field('field,list_field')->where('id', $column['mod_id'])->find();
            if (!empty($mod['list_field'])) {
                $fields     = Fields::field('id,f,fname,fform,fvalue,is_diy')->where([['id', 'in', $mod['list_field']]])->order('list_order DESC,id ASC')->select();
                // 主表字段
                $mainFields = [];
                // 副表字段
                $dataFields = [];
                foreach ($fields as $k => $v) {
                    $listField[] = [
                        'id'     => $v['id'],
                        'f'      => $v['f'],
                        'fname'  => $mod['field'][$v['id']],
                        'is_diy' => $v['is_diy'],
                    ];
                    if ($v['is_diy']) {
                        // 自定义字段，副表
                        $dataFieldsTemp[$v['f']] = [
                            'f'      => $v['f'],
                            'fform'  => $v['fform'],
                            'fvalue' => $v['fvalue'],
                        ];
                    } else {
                        // 系统字段，主表
                        $mainFieldsTemp[$v['f']] = [
                            'f'      => $v['f'],
                            'fform'  => $v['fform'],
                            'fvalue' => $v['fvalue'],
                        ];
                    }
                }
                $dataFields = 'id';
                if (!empty($dataFieldsTemp)) {
                    foreach ($dataFieldsTemp as $v) {
                        $dataFields .= ','.$v['f'];
                    }
                }
                if ($dataFields) {
                    $ids = [];
                    foreach ($data as $v) {
                        $ids[] = $v['id'];
                    }
                    $temp = Db::name($column['tbname'])->field($dataFields)->where([['id', 'in', $ids]])->select();
                    foreach ($temp as $k => $v) {
                        if (!empty($dataFieldsTemp)) {
                            foreach ($dataFieldsTemp as $key => $val) {
                                if (isset($v[$key]) && $v[$key] != '') {
                                    // 字段 form 类型
                                    switch ($val['fform']) {
                                        // Y-m-d 日期格式
                                        case 'timestamp(Y-m-d)':
                                            $v[$key] = date('Y-m-d', $v[$key]);
                                            break;

                                        // Y-m-d H:i:s 日期格式
                                        case 'timestamp(Y-m-d H:i:s)':
                                            $v[$key] = date('Y-m-d H:i:s', $v[$key]);
                                            break;

                                        // select/radio/checkbox
                                        case 'select': case 'radio': case 'checkbox':
                                        if ($val['fvalue']) {
                                            // 拆分字段初始值
                                            $arr   = explode("\r\n", $val['fvalue']);
                                            $value = [];
                                            foreach ($arr as $v1) {
                                                if (strpos($v1, '==') !== false) {
                                                    $arr1 = explode('==', $v1);
                                                    $value[$arr1[0]] = str_replace(':default', '', $arr1[1]);
                                                }
                                            }
                                            if ($value) {
                                                // 拆分字段值
                                                $arr2 = explode(',', $v[$key]);
                                                $str  = '';
                                                foreach ($arr2 as $v2) {
                                                    $str .= $value[$v2].',';
                                                }
                                                $str = trim($str, ',');
                                                $v[$key] = $str;
                                            }
                                        }
                                        break;

                                        // 图片
                                        case 'image':
                                            $v[$key] = '<div class="m-list-pic"><img src="'.attach_uri($v[$key]).'" alt="" /></div>';
                                            break;

                                        // 附件
                                        case 'file':
                                            $v[$key] = '-';
                                            break;

                                        // 相册
                                        case 'photos':
                                            $v[$key] = '-';
                                            break;
                                    }
                                }
                            }
                        }
                        $dataAttach[$v['id']] = $v;
                    }
                }
            }
        }

        $list = [
            'listField'  => $listField,
            'dataAttach' => $dataAttach,
        ];
        return $list;
    }

    /**

     * 获取所有内容

     * @param  array  $where 查询条件

     * @param  string $order 排序条件

     * @param  string $limit 分页条件

     * @return array

     */

    public static function contents($where = [], $order = '', $limit = '')
    {
        $order = $order ?: 'list_order DESC, post_time DESC, id DESC';
        $key   = md5('Contents' . (is_array($where) ? serialize($where) : $where) . $order . $limit);
        $data  = Cache::get($key);
        if (!$data) {
            if (isset($where['id']) || isset($where['url'])) {
                $data = ContentsModel::field(true)->append(['post_time_ymd', 'vice_data'])->where($where)->find();
                /*if($data['vice_data']['content']){

                }*/


            } elseif ($limit == 1) {

                $data = ContentsModel::field(true)->append(['post_time_ymd', 'vice_data'])->where($where)->order($order)->limit(1)->find();

            } else {

                foreach ($where as $k => $v) {

                    if ($v[0] == 'column_id') {

                        $columnIds = isset($v[2]) ? $v[2] : $v[1];

                        $columnIds = is_array($columnIds) ? $columnIds : explode(',', $columnIds);

                        $columns   = ColumnsModel::field('id,is_last')->where([['id', 'in', $columnIds]])->select();

                        $lastIds   = [];

                        foreach ($columns as $column) {

                            if ($column['is_last']) {

                                $temp = [$column['id']];

                            } else {

                                $temp = Columns::getLastColumns(get_sub_ids(ColumnsModel::class, $column['id']));

                            }

                            $lastIds = array_merge($lastIds, $temp);

                        }

                        $lastIds = array_unique($lastIds);

                        if (!empty($lastIds)) {

                            $where[$k] = ['column_id', 'in', $lastIds];

                        }

                    }

                }



                if (!empty($where)) {

                    $data = ContentsModel::field(true)->append(['post_time_ymd', 'vice_data'])->where($where)->order($order)->limit($limit)->select();


                } else {

                    $data = [];

                }

            }

            $data = $data ? $data->toArray() : [];

            Cache::tag('Contents')->set($key, $data);

        }

        return $data;

    }



    /**

     * 获取内容页面模板

     * @param array $where 查询条件

     */

    public static function getTemplate($where)

    {

        $key      = md5('ContentsTemplate'.get_device().serialize($where));

        $template = Cache::get($key);

        if (!$template) {

            $info     = ContentsModel::field('column_id,category_id,pc_template,wap_template')->where($where)->find();

            $template = is_mobile() ? $info['wap_template'] : $info['pc_template'];

            if ($template) {

                Cache::tag('Contents')->set($key, $template);

                return $template;

            }

            if ($info['column_id']) {

                // 栏目信息

                $column   = ColumnsModel::field('content_pc_template,content_wap_template')->where('id', $info['column_id'])->find();

                $template = is_mobile() ? $column['content_wap_template'] : $column['content_pc_template'];

                Cache::tag('Columns')->set($key, $template);

                return $template;

            }

            if ($info['category_id']) {

                // 页面信息

                $template = 'pages_show';

                Cache::tag('Columns')->set($key, $template);

                return $template;

            }

        }

        return $template;

    }



    /**

     * 获取翻页数据

     * @param  string $type     翻页类别，prev: 上一篇；next: 下一篇

     * @param  int    $columnId 栏目 id

     * @param  int    $id       信息 id

     * @return array

     */

    public static function clip($type, $columnId, $id)

    {

        $where = [

            'id' => $id,

        ];

        $key   = md5('ContentsClip'.$type.$columnId.$id);

        $data  = Cache::get($key);

        if ($data === false) {

            $info  = self::contents($where);

            $glt   = $type == 'prev' ? 'lt' : 'gt';

            $order = 'list_order DESC, post_time DESC, id DESC';

            if ($type == 'next') {

                $order = 'list_order ASC, post_time ASC, id ASC';

            }

            $whereOr = [

                [

                    ['column_id', 'eq', $columnId],

                    ['list_order', $glt, $info['list_order']],

                ],

                [

                    ['column_id', 'eq', $columnId],

                    ['list_order', 'eq', $info['list_order']],

                    ['post_time', $glt, strtotime($info['post_time'])],

                ],

                [

                    ['column_id', 'eq', $columnId],

                    ['list_order', 'eq', $info['list_order']],

                    ['post_time', 'eq', strtotime($info['post_time'])],

                    ['id', $glt, $id],

                ],

            ];



            $data = ContentsModel::field('id,title,url')->whereOr($whereOr)->order($order)->find();

            Cache::tag('Contents')->set($key, $data);

        }

        return $data;

    }

	/*
	 * 获取详情
	 * $id	int	文章ID
	 * */
	public function getInfo($userid,$id){
		$where = [
			['id', 'eq', $id]
		];
		$c_mod = new ContentsModel();
		$field = 'id,column_id,title,ftitle,titlepic,post_time,titlepic,actual_browse_nums,comment_nums,create_time,tbname';
		$info = $c_mod->get_info($where,$field,['post_time', 'columns_name','title_pic_url','vice_data']);

		if(empty($info)){
			exception('文章不存在');
		}
		$c_where = [
			['userid', 'eq', $userid],
			['data_id', 'eq', $id],
			['data_type', 'neq', 'product'],//商品product视频video论文paper分享share资料content
		];
		//是否收藏
		$is_collect = CollectionModel::where($c_where)->value('id');
		$info['is_collect'] = 0;
		if($is_collect){
			$info['is_collect'] =1;
		}
		ContentsModel::where('id',$id)->setInc('actual_browse_nums',1);
		return $info;
	}
}
